package org.demo.nio.reactor.multiplereactor;

import sun.reflect.generics.tree.VoidDescriptor;

import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by tangwy on 2017/11/1.
 */
public class SubReactor implements Runnable {
    private volatile Selector selector;
    private ConcurrentLinkedQueue taskQueue=new ConcurrentLinkedQueue();
    public SubReactor(SelectorProvider selectorProvider) throws IOException {
        selector= selectorProvider.openSelector();
    }

    public void register(SocketChannel channel) throws IOException {
        System.out.println("register");
        channel.configureBlocking(false);
        SelectionKey sk = channel.register(selector, SelectionKey.OP_READ);
        sk.attach(new RWHandler(channel,selector));
        selector.wakeup();
    }


    @Override
    public void run() {
        while (!Thread.interrupted()){
            try {
                int count=selector.select(500);
                if(count<=0){
                    continue;
                }
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    System.out.println("子线程run2:" + key.interestOps());
                    process(key);
                }
            } catch (IOException e) {
                //异常处理
                e.printStackTrace();
            }
        }
    }

    private void process(SelectionKey key) {
        Runnable r = (Runnable) key.attachment();
        if(r!=null){
            r.run();
        }
    }

    private void processTaskQueue(){
        for(;;){
            taskQueue.poll();
        }
    }
}
